﻿/*
 * PsTFS is a set of PowerShell commands to manage and use Team Foundation Server. PowerShell 
 * effectiveness is combined with the power of TFS API to maximizes TFS capabilities.
 * 
 * Creator : Choulant Noham
 * Mail : choulant@gmail.com
 * Blog : http://choulant.blogspot.com
 * 
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using PsTFS.Methodes;
using PsTFS.Objects;

namespace PsTFS.Commandes.Get
{
    /// <summary>
    /// Récupération des changesets
    /// </summary>
    [Cmdlet(VerbsCommon.Get, "Changeset")]
    public class GetChangeset : PsCmdlet
    {
        public GetChangeset()
        {
            MaxResults = int.MaxValue;
        }

        /// <summary>
        /// Lancement du processus de récupération de changeset
        /// </summary>
        protected override void ProcessRecord()
        {
            try
            {
                // Get a reference to the version control service
                var versionControl = MethodService.VersionControlServer();
                var results = new List<Changeset>();
                if (!string.IsNullOrEmpty(Path))
                {
                    results = versionControl.QueryHistory(Path, VersionSpec.Latest, 0, RecursionType.Full, null,
                                                FromVersion, ToVersion, int.MaxValue, true, true)
                                  .Cast<Changeset>()
                                  .Where(c => c != null && c.Changes.Length > 0)
                                  .ToList();
                }
                else if (Item != null)
                {
                    var qhp = new QueryHistoryParameters(Item)
                                  {
                                      IncludeChanges = true, 
                                      MaxResults = MaxResults
                                  };
                    results = versionControl.QueryHistory(qhp)
                        .Where(c => c != null && c.Changes.Length > 0)
                        .ToList();
                }

                WriteObject(results, false);
                //WriteObject(
                //    versionControl.QueryHistory(FormattedPath, VersionSpec.Latest, 0, RecursionType.Full, null,
                //                                FromVersion, ToVersion, int.MaxValue, true, true)
                //                  .Cast<Changeset>()
                //                  .Where((c => c != null && c.Changes.Length > 0))
                //                  .ToList());
            }
            catch (Exception ex)
            {
                var err = ErrorRecord(ex, ErrorCategory.WriteError);
                WriteError(err);
                Log.AddLog(ex.StackTrace);
            }
        }

        /// <summary>
        /// Permet d'informer la fin de la commande
        /// </summary>
        protected override void EndProcessing()
        {
            Log.AddLog(null, "Get-Changeset is end");
            base.EndProcessing();
        }

        protected String FormattedPath
        {
            get
            {
                return String.IsNullOrEmpty(Path)
                           ? String.Empty
                           : (!Path.StartsWith("$/'") ? "$/" : "") + Path;
            }
        }
        /// <summary>
        /// Object contenant Team Foundation Server
        /// </summary>
        [Parameter(Position = 0)]
        public TfsTeamProjectCollection TFS
        {
            set { Context.Instance.TFS = value; }
        }
        /// <summary>
        /// Emplacement depuis le quel récupérer les changesets
        /// </summary>
        [Parameter(Position = 1)]
        [ValidateNotNullOrEmpty]
        public String Path{ get; set; }

        // From version spec
        [Parameter(Position = 2)]
        [ValidateNotNullOrEmpty]
        public ItemSpec Item { get; set; }

        // From version spec
        [Parameter(Position = 3)]
        [ValidateNotNullOrEmpty]
        public VersionSpec FromVersion { get; set; }

        // To version spec
        [Parameter(Position = 4)]
        [ValidateNotNullOrEmpty]
        public VersionSpec ToVersion { get; set; }

        [Parameter(Position = 5)]
        [ValidateNotNullOrEmpty]
        public int MaxResults { get; set; }
    }
}